﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using System.Web;
using System.Globalization;
using System.Security.Principal;
using System.Net;
using System.Configuration;
using System.IO;

    

        public enum DateInterval
        {
            Year,
            Month,
            Weekday,
            Day,
            Hour,
            Minute,
            Second
        }

        public class DateTimeUtil
        {

            public static string ConvertirFecha(DateTime Fecha)
            {
                string dateFechaResult = "";

                DateTime FechaInicial = Fecha;



                int intDia = FechaInicial.Day;
                int intMes = FechaInicial.Month;
                int intAnnio = FechaInicial.Year;

                string strDia = "";
                string strMes = "";

                if (intDia < 10) { strDia = "0" + intDia; }
                else { strDia = intDia.ToString(); }
                if (intMes < 10) { strMes = "0" + intMes; }
                else { strMes = intMes.ToString(); }

                dateFechaResult = intAnnio + strMes + strDia;

                return dateFechaResult;
            }


            public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
            {

                TimeSpan ts = date2 - date1;

                switch (interval)
                {
                    case DateInterval.Year:
                        return date2.Year - date1.Year;
                    case DateInterval.Month:
                        return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
                    case DateInterval.Weekday:
                        return Fix(ts.TotalDays) / 7;
                    case DateInterval.Day:
                        return Fix(ts.TotalDays);
                    case DateInterval.Hour:
                        return Fix(ts.TotalHours);
                    case DateInterval.Minute:
                        return Fix(ts.TotalMinutes);
                    default:
                        return Fix(ts.TotalSeconds);
                }
            }

            private static long Fix(double Number)
            {
                if (Number >= 0)
                {
                    return (long)Math.Floor(Number);
                }
                return (long)Math.Ceiling(Number);
            }

            
        }
        public class Util
        {
            //Permite eliminar multiples sessiones a la vez
            public static void RemoverSesiones(params string[] nombreSession)
            {
                for (int i = 0; i < nombreSession.Length; i++)
                {
                    HttpContext.Current.Session.Remove(nombreSession[i]);
                    //HttpContext.Current.Session[nombreSession[i]] = null;
                }
            }
            public static String borrarEspacios(String cadena)
            {
                String cadenaNueva = "";
                foreach (char car in cadena)
                {
                    if (!(car.Equals(' ')))
                    {
                        cadenaNueva += car;
                    }
                }
                return cadenaNueva;
            }
            public static byte[] ReadToEnd(System.IO.Stream stream)
            {
                long originalPosition = 0;

                if (stream.CanSeek)
                {
                    originalPosition = stream.Position;
                    stream.Position = 0;
                }

                try
                {
                    byte[] readBuffer = new byte[4096];

                    int totalBytesRead = 0;
                    int bytesRead;

                    while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                    {
                        totalBytesRead += bytesRead;

                        if (totalBytesRead == readBuffer.Length)
                        {
                            int nextByte = stream.ReadByte();
                            if (nextByte != -1)
                            {
                                byte[] temp = new byte[readBuffer.Length * 2];
                                Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                                Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                                readBuffer = temp;
                                totalBytesRead++;
                            }
                        }
                    }

                    byte[] buffer = readBuffer;
                    if (readBuffer.Length != totalBytesRead)
                    {
                        buffer = new byte[totalBytesRead];
                        Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                    }
                    return buffer;
                }
                finally
                {
                    if (stream.CanSeek)
                    {
                        stream.Position = originalPosition;
                    }
                }
            }

        }

        public static class Extensions
        {
            public static string ToTitleCase(this string texto)
            {
                return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(texto);
            }

            public static string DiaDeLaSemana(this DateTime fecha)
            {
                CultureInfo cInfo = new CultureInfo("es-ES");
                return cInfo.DateTimeFormat.DayNames[DOfW(fecha)].ToTitleCase();
            }

            private static int DOfW(DateTime date)
            {
                int[] mesCode = { 0, 6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
                int result = date.Year % 100 + (date.Year % 100) / 4 + date.Day + mesCode[date.Month];

                if (date.Year / 100 == 17) result += 5;
                else if (date.Year / 100 == 18) result += 3;
                else if (date.Year / 100 == 19) result += 1;
                else if (date.Year / 100 == 20) result += 0;
                else if (date.Year / 100 == 21) result += -2;
                else if (date.Year / 100 == 22) result += -4;

                //Vemos si es bisiesto y quitamos un día si
                //el mes es enero o febrero
                if (EsBisiesto(date.Year) && (date.Month == 1 || date.Month == 2))
                    result += -1;

                //Esto devuelve un número entre 0 y 7
                //que nos dá el día de la semana
                return result % 7;
            }

            //Método para saber si un año es bisiesto
            private static bool EsBisiesto(int a)
            {
                return (a % 4 == 0 && a % 100 != 0) || a % 400 == 0;
            }
        }

        public class CustomFTP
        {
            // local variable for network credential.
            public string _UserName;
            public string _PassWord;
            public string _FtpName;

            public CustomFTP()
            {
                _UserName = ConfigurationManager.AppSettings["FtpUser"];
                _PassWord = ConfigurationManager.AppSettings["FtpPassword"];
                _FtpName = ConfigurationManager.AppSettings["PathFtp"];
            }

            public CustomFTP(string UserName, string PassWord, string DomainName)
            {
                _UserName = UserName;
                _PassWord = PassWord;
                _FtpName = DomainName;
            }
            public WindowsIdentity ImpersonationUser
            {
                get
                {
                    return null;  // not use ImpersonationUser
                }
            }
            public ICredentials NetworkCredentials
            {
                get
                {

                    // use NetworkCredentials
                    return new NetworkCredential(_UserName, _PassWord);
                }
            }
            public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
            {

                // not use FormsCredentials unless you have implements a custom autentication.
                authCookie = null;
                user = password = authority = null;
                return false;
            }

            public byte[] downloadFile(string ftpruta,long size)
            {
                byte[] downloadedData = new byte[0];
                try
                {
                    CustomFTP oCustomFTP = new CustomFTP();
                    //Create FTP request
                    //Note: format is ftp://server.com/file.ext
                    FtpWebRequest request = FtpWebRequest.Create(ftpruta) as FtpWebRequest;
                    //Now get the actual data
                    request = FtpWebRequest.Create(ftpruta) as FtpWebRequest;
                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                    request.Proxy = null;
                    request.Credentials = oCustomFTP.NetworkCredentials;
                    request.UsePassive = true;
                    request.UseBinary = true;
                    request.KeepAlive = false; //close the connection when done
                    //Streams
                    FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                    Stream reader = response.GetResponseStream();
                    //Download to memory
                    //Note: adjust the streams here to download directly to the hard drive
                    MemoryStream memStream = new MemoryStream();
                  
                    byte[] buffer = new byte[size]; //downloads in chuncks
                    while (true)
                    {
                        //Try to read the data
                        int bytesRead = reader.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            break;
                        }
                        else
                        {
                            //Write the downloaded data
                            memStream.Write(buffer, 0, bytesRead);
                        }
                    }
                    //Convert the downloaded stream to a byte array
                    downloadedData = memStream.ToArray();
                    //Clean up
                    reader.Close();
                    memStream.Close();
                    response.Close();
                    //message = “Downloaded Successfully”;
                    //Delete file
                    FtpWebRequest ftp = FtpWebRequest.Create(ftpruta) as FtpWebRequest;
                    ftp.Method = WebRequestMethods.Ftp.DeleteFile;
                    ftp.Proxy = null;
                    ftp.Credentials = oCustomFTP.NetworkCredentials;
                    FtpWebResponse ftpresponse;
                    try
                    {
                        ftpresponse = ftp.GetResponse() as FtpWebResponse;
                        //Console.WriteLine(“Delete status: {0}”, response.StatusDescription);
                        ftpresponse.Close();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                catch (Exception)
                {
                    //throw;
                }

                return downloadedData;
            }

        }

